<template>
  <div class="drama-publish">
    <el-card>
      <template #header>
        <div class="publish-header">
          <h2>短剧发布</h2>
          <p>按照步骤填写短剧信息，完成发布</p>
        </div>
      </template>

      <el-steps :active="activeStep" finish-status="success" align-center>
        <el-step title="基本信息" description="填写短剧基本信息"></el-step>
        <el-step title="媒体资源" description="上传封面、海报等"></el-step>
        <el-step title="分类标签" description="选择分类和标签"></el-step>
        <el-step title="演员信息" description="添加演员和角色"></el-step>
        <el-step title="剧集管理" description="添加剧集信息"></el-step>
        <el-step title="确认发布" description="检查信息并发布"></el-step>
      </el-steps>

      <div class="step-content">
        <!-- 步骤1: 基本信息 -->
        <div v-show="activeStep === 0" class="step-panel">
          <h3>基本信息</h3>
          <el-form :model="dramaForm" :rules="rules.basic" ref="basicFormRef" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="短剧标题" prop="title">
                  <el-input v-model="dramaForm.title" placeholder="请输入短剧标题" maxlength="100" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="副标题" prop="subTitle">
                  <el-input v-model="dramaForm.subTitle" placeholder="请输入副标题" maxlength="100" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="发布日期" prop="releaseDate">
                  <el-date-picker
                    v-model="dramaForm.releaseDate"
                    type="date"
                    placeholder="选择发布日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="总集数" prop="totalEpisodes">
                  <el-input-number v-model="dramaForm.totalEpisodes" :min="1" :max="1000" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="年份" prop="year">
                  <el-input-number v-model="dramaForm.year" :min="1900" :max="2030" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="语言" prop="language">
                  <el-select v-model="dramaForm.language" placeholder="请选择语言" style="width: 100%">
                    <el-option label="中文" value="zh-CN" />
                    <el-option label="英文" value="en-US" />
                    <el-option label="日文" value="ja-JP" />
                    <el-option label="韩文" value="ko-KR" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="地区" prop="region">
                  <el-input v-model="dramaForm.region" placeholder="请输入地区" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="画质" prop="quality">
                  <el-select v-model="dramaForm.quality" placeholder="请选择画质" style="width: 100%">
                    <el-option label="标清(SD)" value="SD" />
                    <el-option label="高清(HD)" value="HD" />
                    <el-option label="全高清(FHD)" value="FHD" />
                    <el-option label="4K" value="4K" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="导演" prop="director">
                  <el-input v-model="dramaForm.director" placeholder="多个导演用逗号分隔" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="编剧" prop="screenwriter">
                  <el-input v-model="dramaForm.screenwriter" placeholder="多个编剧用逗号分隔" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="制作公司" prop="productionCompany">
              <el-input v-model="dramaForm.productionCompany" placeholder="请输入制作公司" />
            </el-form-item>

            <el-form-item label="简介" prop="description">
              <el-input
                v-model="dramaForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入短剧简介"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="剧情介绍" prop="storyLine">
              <el-input
                v-model="dramaForm.storyLine"
                type="textarea"
                :rows="6"
                placeholder="请输入详细剧情介绍"
                maxlength="2000"
                show-word-limit
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="年龄分级" prop="ageRating">
                  <el-select v-model="dramaForm.ageRating" placeholder="请选择年龄分级" style="width: 100%">
                    <el-option label="G (所有年龄)" value="G" />
                    <el-option label="PG (建议家长指导)" value="PG" />
                    <el-option label="PG-13 (13岁以上)" value="PG-13" />
                    <el-option label="R (17岁以上)" value="R" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="是否完结">
                  <el-switch v-model="dramaForm.isFinished" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="VIP专享">
                  <el-switch v-model="dramaForm.isVip" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="推荐">
                  <el-switch v-model="dramaForm.isRecommended" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="热播">
                  <el-switch v-model="dramaForm.isHot" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 步骤2: 媒体资源 -->
        <div v-show="activeStep === 1" class="step-panel">
          <h3>媒体资源</h3>
          <el-form :model="dramaForm" :rules="rules.media" ref="mediaFormRef" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="封面图" prop="cover" required>
                  <div class="upload-container">
                    <el-upload
                      ref="coverUploadRef"
                      :action="uploadUrl"
                      :headers="uploadHeaders"
                      :show-file-list="false"
                      :on-success="(res) => handleUploadSuccess(res, 'cover')"
                      :before-upload="handleBeforeUpload"
                      accept="image/*"
                      class="cover-uploader"
                    >
                      <img v-if="dramaForm.cover" :src="dramaForm.cover" class="cover-image" />
                      <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-tip">建议尺寸：750x1000px，支持jpg、png格式</div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="海报图" prop="poster">
                  <div class="upload-container">
                    <el-upload
                      ref="posterUploadRef"
                      :action="uploadUrl"
                      :headers="uploadHeaders"
                      :show-file-list="false"
                      :on-success="(res) => handleUploadSuccess(res, 'poster')"
                      :before-upload="handleBeforeUpload"
                      accept="image/*"
                      class="poster-uploader"
                    >
                      <img v-if="dramaForm.poster" :src="dramaForm.poster" class="poster-image" />
                      <el-icon v-else class="poster-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                    <div class="upload-tip">建议尺寸：1920x1080px，支持jpg、png格式</div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="预告片" prop="trailerUrl">
              <div class="upload-container">
                <el-upload
                  ref="trailerUploadRef"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="(res) => handleUploadSuccess(res, 'trailerUrl')"
                  :before-upload="handleVideoBeforeUpload"
                  accept="video/*,.dat"
                  class="video-uploader"
                >
                  <div v-if="dramaForm.trailerUrl" class="video-preview">
                    <video :src="dramaForm.trailerUrl" controls style="width: 100%; max-height: 200px;"></video>
                  </div>
                  <div v-else class="video-upload-area">
                    <el-icon class="video-uploader-icon"><VideoCamera /></el-icon>
                    <div class="upload-text">点击上传预告片</div>
                  </div>
                </el-upload>
                <div class="upload-tip">支持mp4、mov、avi、wmv、flv、webm、mkv、dat格式，文件大小不超过100MB</div>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 步骤3: 分类标签 -->
        <div v-show="activeStep === 2" class="step-panel">
          <h3>分类标签</h3>
          <el-form :model="relationForm" ref="categoryFormRef" label-width="120px">
            <el-form-item label="分类选择" required>
              <el-tree
                ref="categoryTreeRef"
                :data="categoryTreeData"
                :props="treeProps"
                show-checkbox
                node-key="categoryId"
                :check-strictly="false"
                :default-expand-all="false"
                :expand-on-click-node="false"
                :check-on-click-node="true"
                :default-checked-keys="relationForm.selectedCategoryIds"
                @check="handleCategoryTreeCheck"
                style="max-height: 300px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px;"
                empty-text="暂无分类数据"
              />
            </el-form-item>

            <el-form-item label="已选分类" v-if="relationForm.selectedCategoryIds?.length > 0">
              <div class="selected-categories">
                <el-tag
                  v-for="categoryId in relationForm.selectedCategoryIds"
                  :key="categoryId"
                  type="primary"
                  style="margin-right: 8px; margin-bottom: 4px;"
                  closable
                  @close="removeCategoryById(categoryId)"
                >
                  {{ getCategoryNameById(categoryId) }}
                </el-tag>
              </div>
            </el-form-item>

            <el-form-item label="标签选择">
              <el-select
                v-model="relationForm.tagIds"
                placeholder="请选择标签（可多选）"
                multiple
                filterable
                style="width: 100%"
                collapse-tags
                collapse-tags-tooltip
              >
                <el-option
                  v-for="tag in filteredTags"
                  :key="tag.tagId"
                  :label="tag.name"
                  :value="tag.tagId"
                >
                  <span style="float: left">{{ tag.name }}</span>
                  <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                    使用: {{ tag.useCount || 0 }}
                  </span>
                </el-option>
              </el-select>
              <div style="margin-top: 8px; color: var(--el-text-color-placeholder); font-size: 12px;">
                <i class="el-icon-info"></i>
                小提示：选择分类后会优先显示该分类下的标签，也可以选择其他标签
              </div>
            </el-form-item>

            <el-form-item label="所选标签" v-if="relationForm.tagIds?.length > 0">
              <el-tag
                v-for="tagId in relationForm.tagIds"
                :key="tagId"
                type="success"
                style="margin-right: 8px; margin-bottom: 4px;"
                closable
                @close="removeTag(tagId)"
              >
                {{ getTagNameById(tagId) }}
              </el-tag>
            </el-form-item>
          </el-form>
        </div>

        <div v-show="activeStep === 3" class="step-panel">
          <h3>演员信息</h3>
          <div class="actor-section">
            <el-button type="primary" @click="showAddActorDialog">添加演员</el-button>

            <el-table :data="relationForm.dramaActors" style="margin-top: 20px;" v-if="relationForm.dramaActors.length > 0">
              <el-table-column prop="actorName" label="演员姓名">
                <template #default="scope">
                  <span>{{ scope.row.actorName }}</span>
                  <el-tag v-if="scope.row.isNewActor" type="warning" size="small" style="margin-left: 8px;">
                    新演员
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="roleName" label="角色名" />
              <el-table-column prop="roleType" label="角色类型">
                <template #default="scope">
                  <el-tag :type="getRoleTypeTag(scope.row.roleType)">{{ getRoleTypeName(scope.row.roleType) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="sortOrder" label="排序" width="80" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button link type="primary" @click="editActor(scope.$index)">编辑</el-button>
                  <el-button link type="danger" @click="removeActor(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="还没有添加演员" />
          </div>
        </div>

        <div v-show="activeStep === 4" class="step-panel">
          <h3>剧集管理</h3>
          <div class="episode-section">
            <el-button type="primary" @click="showAddEpisodeDialog">添加剧集</el-button>

            <el-table :data="episodes" style="margin-top: 20px;" v-if="episodes.length > 0">
              <el-table-column prop="episodeNumber" label="集数" width="80" />
              <el-table-column prop="title" label="标题" />
              <el-table-column prop="duration" label="时长">
                <template #default="scope">
                  {{ formatDuration(scope.row.duration) }}
                </template>
              </el-table-column>
              <el-table-column prop="isFree" label="是否免费" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.isFree ? 'success' : 'warning'">
                    {{ scope.row.isFree ? '免费' : '付费' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="isTrailer" label="是否预告片">
                <template #default="scope">
                  <el-tag :type="scope.row.isTrailer ? 'success' : 'warning'">
                    {{ scope.row.isTrailer ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button link type="primary" @click="editEpisode(scope.$index)">编辑</el-button>
                  <el-button link type="danger" @click="removeEpisode(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="还没有添加剧集" />
          </div>
        </div>

        <div v-show="activeStep === 5" class="step-panel">
          <h3>确认发布</h3>
          <div class="confirm-section">
            <!-- 数据预览区域 -->
            <el-card class="preview-card" style="margin-bottom: 20px;">
              <template #header>
                <div class="card-header">
                  <span>📄 完整数据预览</span>
                  <el-button
                    text
                    type="primary"
                    @click="showJsonPreview = !showJsonPreview"
                  >
                    {{ showJsonPreview ? '隐藏' : '查看' }}JSON数据
                  </el-button>
                </div>
              </template>

              <div v-if="showJsonPreview" class="json-preview">
                <pre><code>{{ JSON.stringify(getFullDramaData(), null, 2) }}</code></pre>
              </div>

              <div v-else class="summary-info">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-statistic title="基本信息" :value="1" suffix="项" />
                  </el-col>
                  <el-col :span="8">
                    <el-statistic title="演员数量" :value="relationForm.dramaActors?.length || 0" suffix="人" />
                  </el-col>
                  <el-col :span="8">
                    <el-statistic title="剧集数量" :value="episodes.length" suffix="集" />
                  </el-col>
                </el-row>

                <el-row :gutter="20" style="margin-top: 16px;">
                  <el-col :span="8">
                    <el-statistic title="已选分类" :value="relationForm.selectedCategoryIds?.length || 0" suffix="个" />
                  </el-col>
                  <el-col :span="8">
                    <el-statistic title="标签数量" :value="relationForm.tagIds?.length || 0" suffix="个" />
                  </el-col>
                  <el-col :span="8">
                    <el-statistic title="剧集数量" :value="episodes.length" suffix="集" />
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <el-descriptions title="短剧信息" :column="2" border>
              <el-descriptions-item label="标题">{{ dramaForm.title }}</el-descriptions-item>
              <el-descriptions-item label="副标题">{{ dramaForm.subTitle || '-' }}</el-descriptions-item>
              <el-descriptions-item label="导演">{{ dramaForm.director || '-' }}</el-descriptions-item>
              <el-descriptions-item label="编剧">{{ dramaForm.screenwriter || '-' }}</el-descriptions-item>
              <el-descriptions-item label="总集数">{{ dramaForm.totalEpisodes }}</el-descriptions-item>
              <el-descriptions-item label="发布日期">{{ dramaForm.releaseDate }}</el-descriptions-item>
              <el-descriptions-item label="语言">{{ dramaForm.language }}</el-descriptions-item>
              <el-descriptions-item label="地区">{{ dramaForm.region || '-' }}</el-descriptions-item>
              <el-descriptions-item label="封面图" :span="2">
                <img v-if="dramaForm.cover" :src="dramaForm.cover" style="width: 100px; height: auto;" />
                <span v-else>-</span>
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions title="分类标签" :column="1" border style="margin-top: 20px;">
              <el-descriptions-item label="所选分类">
                {{ getSelectedCategoryNames() }}
              </el-descriptions-item>
              <el-descriptions-item label="标签">
                {{ getTagNames() }}
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions title="演员信息" :column="1" border style="margin-top: 20px;">
              <el-descriptions-item label="演员列表">
                <div v-if="relationForm.dramaActors?.length > 0">
                  <el-tag
                    v-for="actor in relationForm.dramaActors"
                    :key="actor.actorId"
                    style="margin-right: 8px; margin-bottom: 4px;"
                  >
                    {{ actor.actorName }}（{{ actor.roleName }}）
                  </el-tag>
                </div>
                <span v-else>-</span>
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions title="剧集信息" :column="1" border style="margin-top: 20px;">
              <el-descriptions-item label="剧集数量">{{ episodes.length }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </div>

      <div class="step-actions">
        <el-button v-if="activeStep > 0" @click="previousStep">上一步</el-button>
        <el-button v-if="activeStep < 5" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="activeStep === 5" type="success" :loading="publishLoading" @click="publishDrama">
          发布短剧
        </el-button>
      </div>
    </el-card>

    <!-- 添加演员对话框 -->
    <el-dialog v-model="actorDialog.visible" :title="actorDialog.title" width="600px">
      <el-form :model="actorForm" ref="actorFormRef" label-width="100px">
        <el-form-item label="演员姓名" prop="actorName" required>
          <el-select
            v-model="actorForm.actorName"
            placeholder="请选择或输入演员姓名"
            filterable
            remote
            allow-create
            default-first-option
            :remote-method="searchActors"
            :loading="actorSearchLoading"
            style="width: 100%"
            @change="handleActorNameChange"
          >
            <el-option
              v-for="actor in actors"
              :key="actor.actorId"
              :label="actor.actorName"
              :value="actor.actorName"
              @click="selectExistingActor(actor)"
            />
          </el-select>
          <div class="form-tip" v-if="actorForm.actorId">
            <el-tag type="success" size="small">选择了已有演员</el-tag>
          </div>
          <div class="form-tip" v-else-if="actorForm.actorName">
            <el-tag type="warning" size="small">新演员，将自动创建</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="角色名" prop="roleName" required>
          <el-input v-model="actorForm.roleName" placeholder="请输入角色名" />
        </el-form-item>

        <el-form-item label="角色类型" prop="roleType" required>
          <el-select v-model="actorForm.roleType" placeholder="请选择角色类型" style="width: 100%">
            <el-option label="主角" :value="1" />
            <el-option label="配角" :value="2" />
            <el-option label="客串" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="actorForm.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="actorDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveActor">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加剧集对话框 -->
    <el-dialog v-model="episodeDialog.visible" :title="episodeDialog.title" width="800px">
      <el-form :model="episodeForm" ref="episodeFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="集数" prop="episodeNumber" required>
              <el-input-number v-model="episodeForm.episodeNumber" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题" prop="title" required>
              <el-input v-model="episodeForm.title" placeholder="请输入剧集标题" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="时长(秒)" prop="duration" required>
          <el-input-number v-model="episodeForm.duration" :min="1" style="width: 100%" />
        </el-form-item>

        <el-form-item label="剧集简介" prop="description">
          <el-input
            v-model="episodeForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入剧集简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="封面图" prop="cover">
          <el-upload
            ref="episodeCoverUploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="(res) => handleEpisodeUploadSuccess(res, 'cover')"
            :before-upload="handleBeforeUpload"
            accept="image/*"
            class="episode-cover-uploader"
          >
            <img v-if="episodeForm.cover" :src="episodeForm.cover" class="episode-cover-image" />
            <el-icon v-else class="episode-cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="视频文件" prop="videoUrl" required>
          <el-upload
            ref="episodeVideoUploadRef"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="(res) => handleEpisodeUploadSuccess(res, 'videoUrl')"
            :before-upload="handleVideoBeforeUpload"
            accept="video/*,.dat"
            class="episode-video-uploader"
          >
            <div v-if="episodeForm.videoUrl" class="episode-video-preview">
              <video :src="String(episodeForm.videoUrl)" controls style="width: 100%; max-height: 200px;"></video>
            </div>
            <div v-else class="episode-video-upload-area">
              <el-icon class="episode-video-uploader-icon"><VideoCamera /></el-icon>
              <div class="upload-text">点击上传视频文件</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否免费">
              <el-switch v-model="episodeForm.isFree" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金币价格" v-if="episodeForm.isFree === 0">
              <el-input-number v-model="episodeForm.coinPrice" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否预告片">
              <el-switch v-model="episodeForm.isTrailer" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="episodeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveEpisode">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Publish" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, VideoCamera } from '@element-plus/icons-vue'
import { publishDramaApi } from '@/api/content/publish'

import { listCategories } from '@/api/content/categories'
import { listTags } from '@/api/content/tags'
import { listActors } from '@/api/content/actors'
import { globalHeaders } from '@/utils/request'
import type { DramasForm } from '@/api/content/dramas/types'
import type { CategoriesVO } from '@/api/content/categories/types'
import type { TagsVO } from '@/api/content/tags/types'
import type { ActorsVO } from '@/api/content/actors/types'
import type { EpisodesForm } from '@/api/content/episodes/types'

// 上传配置
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/content/upload'
const uploadHeaders = globalHeaders()

// 步骤控制
const activeStep = ref(0)
const publishLoading = ref(false)
const showJsonPreview = ref(false) // 控制JSON预览显示

// 表单引用
const basicFormRef = ref<FormInstance>()
const mediaFormRef = ref<FormInstance>()
const categoryFormRef = ref<FormInstance>()

// 短剧表单数据
const dramaForm = reactive<DramasForm>({
  title: '',
  subTitle: '',
  cover: '',
  poster: '',
  trailerUrl: '',
  description: '',
  storyLine: '',
  director: '',
  screenwriter: '',
  productionCompany: '',
  releaseDate: '',
  totalEpisodes: 1,
  language: 'zh-CN',
  region: '',
  year: new Date().getFullYear(),
  quality: 'HD',
  ageRating: 'G',
  isFinished: 0,
  isVip: 0,
  isNew: 1,
  isHot: 0,
  isRecommended: 0,
  status: 1,
  auditStatus: 0
})

// 关联表单数据
const relationForm = reactive({
  selectedCategoryIds: [] as string[], // 改为数组，支持多选
  tagIds: [] as string[],
  dramaActors: [] as any[]
})

// 剧集数据
const episodes = ref<EpisodesForm[]>([])

// 选项数据
const categories = ref<CategoriesVO[]>([])
const tags = ref<TagsVO[]>([])
const actors = ref<ActorsVO[]>([])

// 树形分类相关方法
// 处理树形选择器选中
const handleCategoryTreeCheck = (checkedNodes: any, { checkedKeys }: any) => {
  relationForm.selectedCategoryIds = checkedKeys
}

// 移除分类
const removeCategoryById = (categoryId: string) => {
  const index = relationForm.selectedCategoryIds.indexOf(categoryId)
  if (index > -1) {
    relationForm.selectedCategoryIds.splice(index, 1)
    // 同步更新树组件的选中状态
    categoryTreeRef.value?.setCheckedKeys(relationForm.selectedCategoryIds)
  }
}

// 加载树形分类数据
const loadCategoryTree = async () => {
  try {
    // 加载所有分类数据
    const res = await listCategories({
      pageNum: 1,
      pageSize: 1000,
      status: 1
    })

    const allCategories = res.rows || res.data || []
    categories.value = allCategories

    // 构建树形结构
    categoryTreeData.value = buildCategoryTree(allCategories)
  } catch (error) {
    console.error('加载分类数据失败:', error)
    ElMessage.error('加载分类数据失败')
  }
}

// 构建树形结构
const buildCategoryTree = (categories: CategoriesVO[]) => {
  const categoryMap = new Map()
  const tree: any[] = []

  // 先创建映射
  categories.forEach(category => {
    categoryMap.set(category.categoryId, {
      categoryId: category.categoryId,
      name: category.name,
      level: category.level,
      pId: category.pId,
      children: []
    })
  })

  // 构建树形结构
  categories.forEach(category => {
    const node = categoryMap.get(category.categoryId)
    if (category.pId === 0 || category.pId === '0' || !category.pId) {
      // 根节点
      tree.push(node)
    } else {
      // 子节点
      const parent = categoryMap.get(category.pId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  return tree
}

// 树形分类数据
const categoryTreeData = ref<any[]>([])
const categoryTreeRef = ref()

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'categoryId'
}

// 过滤后的标签（根据所选分类进行过滤）
const filteredTags = computed(() => {
  // 如果没有选择分类，显示所有标签
  if (!relationForm.selectedCategoryIds || relationForm.selectedCategoryIds.length === 0) {
    return tags.value
  }

  // 如果选择了分类，显示属于这些分类的标签
  const filtered = tags.value.filter((tag) => relationForm.selectedCategoryIds.includes(String(tag.categoryId)))

  // 如果过滤后没有标签，返回所有标签（防止用户无法选择标签）
  return filtered.length > 0 ? filtered : tags.value
})

// 表单验证规则
const rules = reactive({
  basic: {
    title: [{ required: true, message: '请输入短剧标题', trigger: 'blur' }],
    totalEpisodes: [{ required: true, message: '请输入总集数', trigger: 'blur' }],
    releaseDate: [{ required: true, message: '请选择发布日期', trigger: 'change' }]
  },
  media: {
    cover: [{ required: true, message: '请上传封面图', trigger: 'change' }]
  }
})

// 步骤控制方法
const nextStep = async () => {
  let valid = true

  // 根据当前步骤验证表单
  if (activeStep.value === 0) {
    valid = await validateForm(basicFormRef.value)
  } else if (activeStep.value === 1) {
    valid = await validateForm(mediaFormRef.value)
  }

  if (valid && activeStep.value < 5) {
    activeStep.value++

    // 根据步骤加载对应数据
    await loadStepData(activeStep.value)
  }
}

// 根据步骤加载数据
const loadStepData = async (step: number) => {
  try {
    if (step === 2) {
      // 步骤2：分类标签 - 加载分类和标签数据
      await loadCategoriesAndTags()
    } else if (step === 3) {
      // 步骤3：演员信息 - 如果需要预加载演员数据
      await loadInitialActors()
    }
  } catch (error) {
    console.error('加载步骤数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 加载分类和标签数据
const loadCategoriesAndTags = async () => {
  try {
    console.log('开始加载分类和标签数据...')

    // 加载标签数据
    if (tags.value.length === 0) {
      console.log('正在加载标签数据...')
      const tagRes = await listTags({ pageNum: 1, pageSize: 1000 })
      tags.value = tagRes.rows || tagRes.data || []
      console.log('标签数据加载完成，共', tags.value.length, '条')
    } else {
      console.log('标签数据已存在，共', tags.value.length, '条')
    }

    // 加载树形分类数据
    if (categoryTreeData.value.length === 0) {
      console.log('正在加载分类数据...')
      await loadCategoryTree()
      console.log('分类数据加载完成')
    } else {
      console.log('分类数据已存在')
    }

    console.log('filteredTags计算结果:', filteredTags.value.length, '条')
  } catch (error) {
    console.error('加载分类标签数据失败:', error)
    ElMessage.error('加载分类标签数据失败')
  }
}

// 加载初始演员数据
const loadInitialActors = async () => {
  try {
    // 只有在还没有加载过演员数据时才加载
    if (actors.value.length === 0) {
      const actorRes = await listActors({ pageNum: 1, pageSize: 50 })
      actors.value = actorRes.rows || actorRes.data || []
    }
  } catch (error) {
    console.error('加载演员数据失败:', error)
    // 演员数据加载失败不阻断流程，因为支持手动输入
  }
}

const previousStep = () => {
  if (activeStep.value > 0) {
    activeStep.value--
  }
}

// 表单验证方法
const validateForm = async (formRef?: FormInstance) => {
  if (!formRef) return true

  try {
    await formRef.validate()
    return true
  } catch {
    ElMessage.error('请检查表单信息')
    return false
  }
}

// 上传相关方法
const handleBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

const handleVideoBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  // 检查文件扩展名，支持常见视频格式和 .dat 格式
  const fileName = file.name.toLowerCase()
  const allowedExtensions = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.webm', '.mkv', '.dat']
  const isValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext))

  // 对于常见视频格式，检查 MIME 类型
  const isVideoMimeType = file.type.startsWith('video/')

  // .dat 文件的 MIME 类型可能不是 video/*，所以单独处理
  const isDatFile = fileName.endsWith('.dat')

  const isValidVideo = isVideoMimeType || isDatFile
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isValidExtension) {
    ElMessage.error('只能上传视频文件！支持格式：mp4、mov、avi、wmv、flv、webm、mkv、dat')
    return false
  }

  if (!isLt100M) {
    ElMessage.error('视频大小不能超过100MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (res: any, field: string) => {
  if (res.code === 200) {
    ;(dramaForm as any)[field] = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

// 移除标签
const removeTag = (tagId: string | number) => {
  const index = relationForm.tagIds.findIndex(id => id === tagId)
  if (index > -1) {
    relationForm.tagIds.splice(index, 1)
  }
}

// 获取分类名称
const getCategoryNameById = (categoryId: string | number) => {
  const category = categories.value.find(c => c.categoryId == categoryId)
  return category ? category.name : '未知分类'
}

// 获取标签名称
const getTagNameById = (tagId: string | number) => {
  const tag = tags.value.find(t => t.tagId == tagId)
  return tag ? tag.name : '未知标签'
}

// 获取所选分类名称列表
const getSelectedCategoryNames = () => {
  if (!relationForm.selectedCategoryIds || relationForm.selectedCategoryIds.length === 0) return '-'
  const names = relationForm.selectedCategoryIds.map(id => getCategoryNameById(id))
  return names.join('、')
}

// 获取所选标签名称列表
const getTagNames = () => {
  if (!relationForm.tagIds || relationForm.tagIds.length === 0) return '-'
  const names = relationForm.tagIds.map(id => getTagNameById(id))
  return names.join('、')
}

// 演员相关
const actorDialog = reactive({
  visible: false,
  title: '添加演员'
})

const actorForm = reactive({
  actorId: '',
  actorName: '',
  roleName: '',
  roleType: 1,
  sortOrder: 0
})

const actorFormRef = ref<FormInstance>()
const actorSearchLoading = ref(false)
const editingActorIndex = ref(-1)

const showAddActorDialog = () => {
  editingActorIndex.value = -1
  actorDialog.title = '添加演员'
  resetActorForm()
  actorDialog.visible = true
}

const editActor = (index: number) => {
  editingActorIndex.value = index
  actorDialog.title = '编辑演员'
  const actor = relationForm.dramaActors[index]
  Object.assign(actorForm, actor)
  actorDialog.visible = true
}

const removeActor = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该演员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    relationForm.dramaActors.splice(index, 1)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消
  }
}

const searchActors = async (query: string) => {
  if (!query) return

  try {
    actorSearchLoading.value = true
    const res = await listActors({
      pageNum: 1,
      pageSize: 20,
      actorName: query
    })
    actors.value = res.rows
  } catch (error) {
    console.error('搜索演员失败:', error)
  } finally {
    actorSearchLoading.value = false
  }
}

// 选择已有演员
const selectExistingActor = (actor: ActorsVO) => {
  actorForm.actorId = actor.actorId
  actorForm.actorName = actor.actorName
}

// 处理演员姓名变化
const handleActorNameChange = (value: string) => {
  // 检查是否选择了已有演员
  const existingActor = actors.value.find(a => a.actorName === value)
  if (existingActor) {
    actorForm.actorId = existingActor.actorId
  } else {
    // 新演员，清空ID
    actorForm.actorId = ''
  }
}

const saveActor = async () => {
  try {
    await actorFormRef.value?.validate()

    // 验证演员姓名
    if (!actorForm.actorName.trim()) {
      ElMessage.error('请输入演员姓名')
      return
    }

    // 检查是否重复添加同一个演员的同一个角色
    const isDuplicate = relationForm.dramaActors.some((actor, index) => {
      if (editingActorIndex.value >= 0 && index === editingActorIndex.value) {
        return false // 编辑时排除自己
      }
      return actor.actorName === actorForm.actorName && actor.roleName === actorForm.roleName
    })

    if (isDuplicate) {
      ElMessage.error('该演员的该角色已存在')
      return
    }

    const actorData = {
      ...actorForm,
      // 如果没有actorId，说明是新演员，后台会自动创建
      isNewActor: !actorForm.actorId
    }

    if (editingActorIndex.value >= 0) {
      // 编辑
      relationForm.dramaActors[editingActorIndex.value] = actorData
    } else {
      // 新增
      relationForm.dramaActors.push(actorData)
    }

    actorDialog.visible = false

    if (actorData.isNewActor) {
      ElMessage.success(`保存成功，新演员"${actorForm.actorName}"将自动创建`)
    } else {
      ElMessage.success('保存成功')
    }
  } catch {
    ElMessage.error('请检查表单信息')
  }
}

const resetActorForm = () => {
  actorForm.actorId = ''
  actorForm.actorName = ''
  actorForm.roleName = ''
  actorForm.roleType = 1
  actorForm.sortOrder = 0
}

const getRoleTypeName = (type: number) => {
  const roleTypes = { 1: '主角', 2: '配角', 3: '客串' }
  return roleTypes[type] || '未知'
}

const getRoleTypeTag = (type: number) => {
  const tagTypes = { 1: 'danger', 2: 'warning', 3: 'info' }
  return tagTypes[type] || 'info'
}

// 剧集相关
const episodeDialog = reactive({
  visible: false,
  title: '添加剧集'
})

const episodeForm = reactive<EpisodesForm>({
  episodeNumber: 1,
  title: '',
  cover: '',
  duration: 0,
  description: '',
  videoUrl: '',
  isFree: 1,
  isTrailer: 0,
  coinPrice: 0
})

const episodeFormRef = ref<FormInstance>()
const editingEpisodeIndex = ref(-1)

const showAddEpisodeDialog = () => {
  editingEpisodeIndex.value = -1
  episodeDialog.title = '添加剧集'
  resetEpisodeForm()
  episodeDialog.visible = true
}

const editEpisode = (index: number) => {
  editingEpisodeIndex.value = index
  episodeDialog.title = '编辑剧集'
  const episode = episodes.value[index]
  Object.assign(episodeForm, episode)
  episodeDialog.visible = true
}

const removeEpisode = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该剧集吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    episodes.value.splice(index, 1)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消
  }
}

const saveEpisode = async () => {
  try {
    await episodeFormRef.value?.validate()

    const episodeData = { ...episodeForm }

    if (editingEpisodeIndex.value >= 0) {
      // 编辑
      episodes.value[editingEpisodeIndex.value] = episodeData
    } else {
      // 新增
      episodes.value.push(episodeData)
    }

    episodeDialog.visible = false
    ElMessage.success('保存成功')
  } catch {
    ElMessage.error('请检查表单信息')
  }
}

const resetEpisodeForm = () => {
  episodeForm.episodeNumber = episodes.value.length + 1
  episodeForm.title = ''
  episodeForm.cover = ''
  episodeForm.duration = 0
  episodeForm.description = ''
  episodeForm.videoUrl = ''
  episodeForm.isFree = 1
  episodeForm.coinPrice = 0
}

const handleEpisodeUploadSuccess = (res: any, field: string) => {
  if (res.code === 200) {
    ;(episodeForm as any)[field] = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}分${remainingSeconds}秒`
}

// 获取完整的提交数据结构
const getFullDramaData = () => {
  return {
    // 基本信息
    drama: {
      ...dramaForm
    },
    // 分类关联（改为多选分类）
    categories: relationForm.selectedCategoryIds,
    // 标签关联
    tags: relationForm.tagIds,
    // 演员信息
    actors: relationForm.dramaActors,
    // 剧集信息
    episodes: episodes.value
  }
}
const publishDrama = async () => {
  try {
    publishLoading.value = true

    // 构建完整的提交数据结构
    const fullDramaData = {
      // 基本信息
      drama: {
        ...dramaForm
      },
      // 分类关联（改为多选分类）
      categories: relationForm.selectedCategoryIds,
      // 标签关联
      tags: relationForm.tagIds,
      // 演员信息
      actors: relationForm.dramaActors,
      // 剧集信息
      episodes: episodes.value
    }

    // 输出完整的JSON数据到控制台，方便调试
    console.log('=== 完整的短剧发布数据 ===', JSON.stringify(fullDramaData, null, 2))

    // 验证必要数据
    if (!fullDramaData.drama.title) {
      ElMessage.error('请填写短剧标题')
      return
    }

    if (!fullDramaData.episodes || fullDramaData.episodes.length === 0) {
      ElMessage.error('请至少添加一个剧集')
      return
    }

    // 调用发布接口
    const res = await publishDramaApi(fullDramaData)

    if (res.code === 200) {
      console.log('=== 短剧发布完成 ===')
      ElMessage.success('短剧发布成功!')

      // 重置表单
      resetForm()
    } else {
      ElMessage.error(res.msg || '发布失败')
    }

  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请重试')
  } finally {
    publishLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  activeStep.value = 0

  // 重置短剧表单
  Object.keys(dramaForm).forEach(key => {
    if (typeof dramaForm[key] === 'string') {
      dramaForm[key] = ''
    } else if (typeof dramaForm[key] === 'number') {
      dramaForm[key] = 0
    }
  })

  // 设置默认值
  dramaForm.totalEpisodes = 1
  dramaForm.language = 'zh-CN'
  dramaForm.year = new Date().getFullYear()
  dramaForm.quality = 'HD'
  dramaForm.ageRating = 'G'
  dramaForm.isNew = 1
  dramaForm.status = 1

  // 重置关联表单
  relationForm.selectedCategoryIds = []
  relationForm.tagIds = []
  relationForm.dramaActors = []

  // 重置剧集
  episodes.value = []

  // 清空缓存的数据，下次需要时重新加载
  tags.value = []
  actors.value = []
  categories.value = []
  categoryTreeData.value = []
}

// 初始化数据（只加载基本配置）
const initData = async () => {
  try {
    console.log('初始化数据...')
    // 初始化树形组件，不预加载分类数据
    categoryTreeData.value = []

    // 预加载标签数据，这样即使用户直接跳到第2步，标签数据也能正常显示
    if (tags.value.length === 0) {
      console.log('预加载标签数据...')
      const tagRes = await listTags({ pageNum: 1, pageSize: 1000 })
      tags.value = tagRes.rows || tagRes.data || []
      console.log('标签数据预加载完成，共', tags.value.length, '条')
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化失败')
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initData()
})
</script>
<style scoped>
.drama-publish {
  padding: 20px;
}

.publish-header {
  text-align: center;
}

.publish-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.publish-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.step-content {
  margin: 40px 0;
  min-height: 400px;
}

.step-panel {
  background: #f9f9f9;
  padding: 30px;
  border-radius: 8px;
}

.step-panel h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.step-actions {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
}

.step-actions .el-button {
  margin: 0 10px;
}

/* 上传组件样式 */
.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cover-uploader, .poster-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s;
  width: 200px;
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-uploader:hover, .poster-uploader:hover {
  border-color: #409eff;
}

.cover-image, .poster-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-uploader-icon, .poster-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.video-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s;
  width: 100%;
  min-height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-uploader:hover {
  border-color: #409eff;
}

.video-upload-area {
  text-align: center;
  padding: 20px;
}

.video-uploader-icon {
  font-size: 48px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  text-align: center;
}

.video-preview {
  width: 100%;
}

/* 演员和剧集区域样式 */
.actor-section, .episode-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

/* 确认发布区域 */
.confirm-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

/* 剧集上传样式 */
.episode-cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s;
  width: 120px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.episode-cover-uploader:hover {
  border-color: #409eff;
}

.episode-cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.episode-cover-uploader-icon {
  font-size: 20px;
  color: #8c939d;
}

.episode-video-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s;
  width: 100%;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.episode-video-uploader:hover {
  border-color: #409eff;
}

.episode-video-upload-area {
  text-align: center;
  padding: 15px;
}

.episode-video-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  margin-bottom: 8px;
}

.episode-video-preview {
  width: 100%;
}

/* 树形选择器样式 */
.selected-categories {
  margin-top: 10px;
  min-height: 32px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.selected-categories .el-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

/* 表单提示样式 */
.form-tip {
  margin-top: 5px;
}

.form-tip .el-tag {
  font-size: 12px;
}
@media (max-width: 768px) {
  .step-panel {
    padding: 20px 15px;
  }

  .cover-uploader, .poster-uploader {
    width: 150px;
    height: 200px;
  }
}

/* 分类标签样式 */
.el-cascader {
  width: 100%;
}

.category-tags {
  margin-top: 10px;
}

.category-tags .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-selection {
  margin-top: 10px;
}

.selected-tags {
  margin-top: 10px;
  min-height: 32px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.selected-tags .el-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

/* JSON预览样式 */
.preview-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.json-preview {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
}

.json-preview pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 12px;
  line-height: 1.4;
  color: #333;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.summary-info {
  padding: 16px;
  background-color: #fafbfc;
  border-radius: 6px;
}
</style>
